package com.adonis.ejoy.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.adonis.ejoy.Item.Follow;
import com.adonis.ejoy.Item.Post;
import com.adonis.ejoy.R;
import com.adonis.ejoy.adapter.FollowAdapter;
import com.adonis.ejoy.adapter.PostAdapter;
import com.adonis.ejoy.utils.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HomeFragment extends Fragment {

    private String baseURL;
    private int uid;
    private List<Post> postList = new ArrayList<>();
    private List<Follow> followList = new ArrayList<>();
    private PostAdapter adapter_post;
    private FollowAdapter adapter_follow;

    private View view=null;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipe_refresh;
    @BindView(R.id.PostList)
    RecyclerView list_posts;              //动态的列表
    @BindView(R.id.list_follows)
    RecyclerView list_follows;              //关注的人的列表

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this,view);
        baseURL = view.getContext().getString(R.string.baseURL);
        toolbar.setTitle("");                          //隐藏系统自带的标题，只显示自己定义的控件
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);    //setSupportActionBar()方法是AppCompatActivity特有的方法
        onCreateItem();
        swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshItems();
            }
        });
        return view;
    }

    private void refreshItems() {
        new Thread(new Runnable(){
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable(){  //对UI的更新只能在主线程中更新，runOnUiThread方法只能通过Activity对象调用
                    @Override
                    public void run() {
                    initFollows();
                    initPost();
                    adapter_post.notifyDataSetChanged();
                    adapter_follow.notifyDataSetChanged();
                    swipe_refresh.setRefreshing(false);
                    }
                });
            }
        }).start();
    }

    /*private void changeList() {
        popStarList.clear();
        for (int i = 0; i < 2; i++) {
            PopStar huangbo = new PopStar("huangbo", R.drawable.huangbo);
            popStarList.add(huangbo);
            PopStar linxinru = new PopStar("linxinru", R.drawable.linxinru);
            popStarList.add(linxinru);
            PopStar liuyifei = new PopStar("liuyifei", R.drawable.liuyifei);
            popStarList.add(liuyifei);
            PopStar baby = new PopStar("baby", R.drawable.baby);
            popStarList.add(baby);
        }
        initPost();
    }*/

    private void onCreateItem() {
        uid = ((TextView)getActivity().findViewById(R.id.user_info)).getMaxWidth();
        initPost();
        LinearLayoutManager layoutManager=new LinearLayoutManager(getActivity());  //new一个线性布局管理器
        list_posts.setLayoutManager(layoutManager);
        list_posts.setNestedScrollingEnabled(false);                             //关闭NestedScroll对recyclerView滑动监听，一次解决滑动冲突
        /*adapter_post =new PostAdapter(postList);
        list_posts.setAdapter(adapter_post);*/


        initFollows();
        LinearLayoutManager layoutManager_list=new LinearLayoutManager(getActivity());  //一个线性布局只能被使用一次
        layoutManager_list.setOrientation(LinearLayoutManager.HORIZONTAL);    //设置滚动控件内的元素为水平排列
        list_follows.setLayoutManager(layoutManager_list);
        /*adapter_follow=new FollowAdapter(followList);
        list_follows.setAdapter(adapter_follow);*/
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.obj instanceof List){
                switch (msg.what){
                    case 1:
                        postList = (List<Post>) msg.obj;
                        adapter_post =new PostAdapter(postList,getActivity());
                        list_posts.setAdapter(adapter_post);
                        break;
                    case 2:
                        followList = (List<Follow>) msg.obj;
                        adapter_follow=new FollowAdapter(followList);
                        list_follows.setAdapter(adapter_follow);;
                        break;
                }
            }
        }
    };

    private void initFollows() {
        //此功能是获取当前账户关注的人的列表
        final String url = baseURL + "mvc/follow?&uid=" + uid;
        HttpUtil.sendGetRequest(url,new Callback() {             //发送网络请求不能在主线程中进行
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("onFailure: ", "failed");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call,final Response response) throws IOException {
                String jsonData = response.body().string();
                Gson gson = new Gson();
                followList = gson.fromJson(jsonData,new TypeToken<List<Follow>>(){}.getType());  //将JSON数组解析为Post集合
                Message message = new Message();
                message.obj = followList;
                message.what = 2;          //followlist
                handler.sendMessage(message);
            }
        });
    }

    private void initPost(){
        final String url = baseURL + "mvc/upload?&UID=" + uid;
        HttpUtil.sendGetRequest(url,new Callback() {             //发送网络请求不能在主线程中进行
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("onFailure: ", "failed");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call,final Response response) throws IOException {
                String jsonData = response.body().string();
                Gson gson = new Gson();
                postList = gson.fromJson(jsonData,new TypeToken<List<Post>>(){}.getType());  //将JSON数组解析为Post集合
                Message message = new Message();
                message.what = 1;       //postlist
                message.obj = postList;
                handler.sendMessage(message);
                //Log.d("postList", postList.toString());
            }
        });
    }

}
